<template>
	<view style="height: 100%; width: 100%" class="map-style-box">
		<view id="mapView" />
		<view class="waterXi" v-show="isShowWaterXi">
			<view class="icon-type mt20" :class="{ 'icon-type-ac': isChoseWaterXi }" style="width: 80rpx" @click="addWaterXi">
				<i :class="`iconfont icon-a-heliu11  fs28`" style="font-size: 34rpx; font-weight: 550"></i>
				<text class="mt7 text nop fs26"> 水系</text>
			</view>
		</view>

		<view
			class="map-title-list"
			:class="{
				'map-t-right': titlePos == 'right',
				'map-t-left': titlePos == 'left',
				'map-t-center': titlePos == 'center'
			}"
			:style="{ color: mapType == 'img' ? '#fff' : '#000' }"
		>
			<view v-for="item in titles" :key="item.key" class="map-title-view">
				{{ item.title }}
			</view>
		</view>
	</view>
</template>
<script>
	import config from '@/static/config.js'
	import L from 'leaflet'
	import '@/static/js/leaflet/leaflet.provider.min.js'
	// import 'leaflet/dist/leaflet.css'
	import '@/static/js/leaflet/leaflet.baseLayerGroup.min.js'

	import 'leaflet.markercluster'
	import { mapActions } from 'vuex'

	import '@/static/js/leaflet/ZoomControlledFeatureGroup.js'

	// 台风插件
	import '@/static/js/leaflet/leaflet.collision.min.js'
	import '@/static/js/leaflet/leaflet.typhoon.min.js'
	import '@/static/js/leaflet/leaflet.imageLayer.min.js'
	import m1 from '@/static/image/map/m2.png'

	import indexApi from '@/api/index.js'
	window.L = L

	export default {
		name: '',
		components: {},
		props: {
			titlePos: {
				type: String,
				default: () => 'right'
			},
			isSearch: {
				type: Boolean,
				default: true
			},
			defaultBase: {
				type: String,
				default: () => 'img'
			},
			// 是否加载边界
			defaultBounds: {
				type: Boolean,
				default: true
			},
			isShowWaterXi: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				mapType: '',
				titles: [
					// { title: 'map表示提', key: 'demo' },
					// { title: '台风2', key: 'dem2o' },
				],
				isChoseWaterXi: false
				// 地图 底图切换，只有
			}
		},
		methods: {
			...mapActions({
				getBounds: 'getBounds'
			}),
			ceshi() {
				this.map.invalidateSize()
			},
			async initMap() {
				// 默认初始化
				const providerGroupId = config.defalutProviderGroupId
				const providerGroup = config.providerGroups[providerGroupId]
				const crs = L.TileLayer.Provider.providers[providerGroup.providers[0]].options.crs || L.CRS.EPSG3857
				const mapOptions = L.Util.extend({}, config.mapOptions, { crs: crs })

				let map = L.map('mapView', mapOptions)
				this.map = map

				this.mapGroups = L.baseLayerGroup().addTo(map)

				this.mapType = this.baseGroup
				this.baseGroup = new L.featureGroup().addTo(map)
				// 默认加载影像
				this.defaultBase == 'img' ? this.initImg() : this.initVec()
				// this.initImg()

				const boundJson = await fetch('/static/points.json')
				console.info(`boundJson:`, boundJson)
				window.boundJson = await boundJson.json()
				// emit出去
				this.$emit('mapDone', map, L)
				// 容器修正
				this.$nextTick(() => {
					map.invalidateSize()
				})
				// this.map = map
				// this.getBoundsByCode()
			},
			// 加载矢量
			initVec() {
				this.mapType = 'vec'
				this.baseGroup.clearLayers()
				const providerGroup = config.providerGroups['TianDiTu_VEC_WMTS']
				providerGroup.providers.forEach((element) => {
					L.tileLayer.provider(element, providerGroup.options).addTo(this.baseGroup)
				})
				this.initCityBounds(true)
			},
			// 加载影像
			initImg() {
				this.mapType = 'img'
				this.baseGroup.clearLayers()
				const providerGroup = config.providerGroups['TianDiTu_IMG_WMTS']
				providerGroup.providers.forEach((element) => {
					L.tileLayer.provider(element, providerGroup.options).addTo(this.baseGroup)
				})
				this.initCityBounds(false)
			},
			setTitle(data, key) {
				if (!key) {
					this.titles = data
				} else {
					const index = this.titles.findIndex((item) => {
						return item.key == key
					})
					if (index > -1) {
						this.titles.title = data
					}
				}
			},
			async initCityBounds(isVec = false) {
				if (!this.defaultBounds) {
					return
				}
				if (!this.boudnJson) {
					let resp = null
					if (this.UserInfoData.dept.code == '350400000000') {
						resp = await indexApi.getCity()
					} else if (this.UserInfoData.dept.parentCode == '350400000000') {
						// 县市用户
						resp = await indexApi.getCounty()
						resp.features = resp.features.filter((el) => el.properties.code == this.UserInfoData.dept.code)
						// resp
					} else {
						resp = await indexApi.getTown()
						resp.features = resp.features.filter((el) => el.properties.code == this.UserInfoData.dept.code)
					}
					this.boudnJson = L.geoJSON(resp, {
						pane: 'tilePane',
						style: function (feature) {
							return { fill: true, fillOpacity: 0, weight: 3, color: isVec ? '#0000ff' : '#fff' }
						}
					}).addTo(this.map)
					this.map.fitBounds(this.boudnJson.getBounds())
					this.initTownLine()
				} else {
					this.boudnJson.setStyle({
						color: isVec ? '#0000ff' : '#fff'
					})
				}
			},
			async initTownLine(isVec = true) {
				if (this.UserInfoData.dept.code == '350400000000') {
					let towngroup = L.zoomControlledFeatureGroup(null, 10, 15)
					let resp = await indexApi.getTown()
					let ly1 = L.geoJSON(resp, {
						pane: 'tilePane',
						style: function (feature) {
							return {
								fill: false,
								fillOpacity: 0,
								weight: 1,
								opacity: 0.2,
								color: isVec ? '#222' : '#fff'
							}
						}
					})
					towngroup.addLayer(ly1)
					towngroup.addTo(this.map)
					let xiangroup = L.zoomControlledFeatureGroup(null, 7, 10)
					let Countyresp = await indexApi.getCounty()
					let ly2 = L.geoJSON(Countyresp, {
						pane: 'tilePane',
						style: function (feature) {
							return {
								fill: false,
								fillOpacity: 0,
								weight: 1,
								opacity: 0.5,
								color: isVec ? '#222' : '#fff'
							}
						}
					})
					xiangroup.addLayer(ly2) //.addTo(xiangroup)
					xiangroup.addTo(this.map)
					return
				}
				if (this.UserInfoData.dept.parentCode == '350400000000') {
					let towngroup = L.zoomControlledFeatureGroup(null, 10, 15)
					let resp = await indexApi.getTown()
					let ly1 = L.geoJSON(resp, {
						pane: 'tilePane',
						style: function (feature) {
							return {
								fill: false,
								fillOpacity: 0,
								weight: 1,
								opacity: 0.2,
								color: isVec ? '#222' : '#fff'
							}
						}
					})
					towngroup.addLayer(ly1)
					towngroup.addTo(this.map)
				}
			},
			async getBoundsByCode(code) {
				let json = await this.getBounds()
				// let json = gcoord.transform(json, gcoord.WGS84, gcoord.BD09)
				if (this.boundsLayer) {
					// this.boundsLayer = L.featureGroup().addTo(this.map)
					this.boundsLayer.remove()
					this.map.removeLayer(this.boundsLayer)
					// this.canvas.remove()
				}
				let areaCodes = [
					'350402',
					'350403',
					'350421',
					'350423',
					'350424',
					'350425',
					'350426',
					'350427',
					'350428',
					'350429',
					'350430',
					'350481'
				]
				this.boundsLayer = L.geoJSON(json, {
					pane: 'tilePane',
					filter: function (geoJsonFeature) {
						let XNO = geoJsonFeature.properties.XZQDM.slice(0, 6)
						if (code == '350400' && areaCodes.includes(XNO)) {
							return true
						}
						// if (code == '350400' || !code) {
						// 	return true
						// }
						if (code == XNO) {
							return true
						}
					},
					style: function (feature) {
						return { fill: false, fillOpacity: 0, weight: 1, color: '#4c4848' }
					}
				})
					.setStyle({
						className: 'mapLine' // 手势设置
					})
					.addTo(this.map)
			},
			filterArr(arr) {
				if (arr.length > 0) {
					arr.map((item) => {
						item = [item[1], item[0]]
						return item
					})
				}
			},

			// 地区定位
			async getMarkerData(isadd = true, latitude, longitude) {
				console.info(`latitude, longitude:`, latitude, longitude)
				if (this.markerLayer) {
					this.map.removeLayer(this.markerLayer)
				}
				if (!isadd) {
					if (this.markerLayer) {
						this.map.removeLayer(this.markerLayer)
					}
					return
				}

				var myIcon = L.icon({
					iconUrl: m1,
					iconSize: [20, 32],
					iconAnchor: [10, 35]
				})
				this.markerLayer = L.marker([latitude, longitude], {
					icon: myIcon
				})
				this.markerLayer.addTo(this.map)
				this.map.flyTo([latitude, longitude], 10)
			},

			addWaterXi() {
				this.isChoseWaterXi = !this.isChoseWaterXi
				this.initWaterXi(this.isChoseWaterXi)
			},
			// 加载水系
			async initWaterXi(checked) {
				if (!this.waterXi && checked) {
					uni.showLoading({
						title: '正在加载'
					})
					let params = {
						service: 'WFS',
						request: 'GetFeature',
						version: '1.0.0',
						outputFormat: 'application/json',
						maxFeatures: '10000',
						typeName: 'sanming:river'
					}
					const resp = await indexApi.geoserver(params)
					this.$hideLoading()
					this.waterXi = L.geoJSON(resp, {
						style: {
							color: '#4FC3F7',
							weight: 2
						}
					})
					// .on('click', (e) => {
					// 	console.info(`e:`, e)
					// })
					this.waterXi.eachLayer((layer) => {
						let properties = layer.feature.properties
						let tip = `
		         <div class='popup-sdz-box'>
		                       <div>河流名:${properties['河流名'] || '-'}</div>
		                       <div>流经乡:${properties['流经乡']}</div>
							   <div>流经县:${properties['流经县']}</div>
							   <div>流长㎞:${properties['流长㎞']}</div>
		                       </div>
		         `
						layer.bindPopup(tip, {
							className: 'demo-popup-waterXi'
						})
					})

					this.waterXi.addTo(this.map)
					return
				}

				if (checked) {
					this.map.addLayer(this.waterXi)
				} else {
					this.map.removeLayer(this.waterXi)
				}
			}
		},
		mounted() {
			this.initMap()
			// let Height = document.body.offsetHeight
			// window.onresize = function () {
			// 	document.body.style.height = Height + 'px'
			// }
		}
	}
</script>
<style lang="scss">
	// @import 'leaflet.markercluster/dist/MarkerCluster.css';
	// @import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
	.map-style-box {
		position: relative;
		background: #9bcffa;
		overflow: hidden;

		//   border: 2rpx solid red;
		.search-map-place {
			position: absolute;
			display: flex;
			left: 12rpx;
			top: 65rpx;
			z-index: 999999999;
			width: 73rpx;

			.s-icon {
				width: 30rpx;
			}
		}

		.map-s-input {
			background: rgba(0, 0, 0, 0.2);
			border-radius: 10rpx;
			color: #ffffff;
			-webkit-backdrop-filter: blur(2px);
			backdrop-filter: blur(2px);
			justify-content: center;
			z-index: 99999;
			width: 500rpx;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			transition: 0.2s;

			.input {
				text-indent: 20rpx;
				color: #ffffff;
			}
		}
	}

	#mapView {
		height: 100%;
		width: 100%;
		background: #9bcffa;
	}

	/deep/.leaflet-tile-pane {
		.leaflet-layer {
			z-index: 0 !important;
		}
	}

	.map-title-list {
		position: absolute;
		top: 20rpx;
		right: 60rpx;
		// left: 50%;
		// transform: translateX(-50%);
		z-index: 10000;
		font-size: 26rpx;
		font-weight: bold;

		.map-title-view {
			white-space: nowrap;
			text-align: center;
		}
	}
	.map-t-right {
		right: 60rpx;
	}
	.map-t-left {
		left: 60rpx;
	}
	.map-t-center {
		left: 50%;
		transform: translateX(-50%);
	}
	/deep/.demo-popup-waterXi {
		.popup-sdz-box {
			display: flex;
			flex-direction: column;
			justify-content: flex-start;
			align-items: flex-start;
		}
		.leaflet-popup-content {
			margin: 10px 15px;
		}
		.leaflet-popup-content-wrapper {
			color: #fff;
			text-align: center;
			background: rgba(0, 0, 0, 0.65);
			border: 1px solid #0085ff;
			box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.18);
			backdrop-filter: blur(5px);
		}
		.leaflet-popup-tip {
			background: rgba(0, 0, 0, 0.65);
			border: 1px solid #0085ff;
			box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.18);
			backdrop-filter: blur(5px);
		}
		.leaflet-popup-close-button {
			color: #fff;
		}
	}

	.waterXi {
		position: absolute;
		display: flex;
		z-index: 999;
		width: 73rpx;
		right: 10rpx;
		bottom: 160rpx;
	}

	/deep/.ty-icon-rote {
		.ty-icon-rote-img {
			animation: spin 3s linear infinite;
		}
	}
	@keyframes spin {
		from {
			transform: rotate(360deg);
		}
		to {
			transform: rotate(0deg);
		}
	}
</style>
